#pragma once
#include <iostream>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <functional>
#include <memory>

#include "InterAddr.hpp"
#include "Log.hpp"

// 模板方法模式

namespace socket_ns
{
    class Socket;
    const static int gbacklog = 8;
    using socket_sptr = std::shared_ptr<Socket>;

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        USAGE_ERROR,
        LISTEN_ERROR
    };

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(InterAddr &addr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual socket_sptr Accpeter(InterAddr *addr) = 0;
        virtual bool Connector(InterAddr &addr) = 0;
        virtual void SetSocketAddrReuse() = 0;// 设置地址复用
        virtual int SockFd() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(std::string &in) = 0;
        virtual void Close() = 0;


    public:
        void BuidListenSocket(InterAddr &addr)
        {
            CreateSocketOrDie();
            SetSocketAddrReuse();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }

        bool BuidClientSocket(InterAddr &addr)
        {
            CreateSocketOrDie();
            return Connector(addr);
        }
        // void BuidUdpSocket()
        // {
        //     CreateSocketOrDie();
        //     BindSocketOrDie();
        // }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int fd = -1) : _sockfd(fd)
        {
            std::cout << "TcpSocket" << std::endl;
        }
        void CreateSocketOrDie() override
        {
            // 1. 创建流式套接字
            std::cout << "CreateSocketOrDie::create sockfd" << std::endl;
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd == -1)
            {
                LOG(FATAL, "socket error");
                exit(SOCKET_ERROR);
            }
            LOG(DEBUG, "socket create success, sockfd is : %d\n", _sockfd);
        }

        void BindSocketOrDie(InterAddr &addr) override
        {
            // 2. bind
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = ::bind(_sockfd, (const struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error");
                exit(BIND_ERROR);
            }
            LOG(DEBUG, "bind success, sockfd is : %d\n", _sockfd);
        }

        void ListenSocketOrDie() override
        {
            // 3. TCP是面向连接的，所以在通信之前，必须建立连接，服务器是被连接
            //     tcpserver 启动，要一直等待用户的连接
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(FATAL, "listen error");
                exit(LISTEN_ERROR);
            }
            LOG(DEBUG, "listen success, sockfd is : %d\n", _sockfd);
        }
        socket_sptr Accpeter(InterAddr *addr) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // listensock只是用来监听的，具体的服务是accept返回的文件描述符来服务的。（服务员案例）
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                return nullptr;
            }
            *addr = peer;
            socket_sptr sock = std::make_shared<TcpSocket>(sockfd); // 多态
            return sock;
        }

        bool Connector(InterAddr &addr) override
        {
            struct sockaddr_in server;
            // 构建目标主机socket信息
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(addr.Port());
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());
            // 发起连接
            int n = connect(_sockfd, (const struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                std::cerr << "connect error" << std::endl;
                exit(3);
            }
            return true;
        }

        int SockFd() override
        {
            return _sockfd;
        }
        void SetSocketAddrReuse() override// 设置地址复用
        {
            int opt = 1;
            ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        }

        int Recv(std::string *out) override
        {
            char buffer[4096];
            // 网路中read读到的是实际读到的字节个数
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                *out = buffer; // 重点
            }

            return n;
        }

        int Send(std::string &in) override
        {
            int n = ::send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }
        void Close() override
        {
            if (_sockfd > -1)
                ::close(_sockfd);
        }



    private:
        int _sockfd;
    };
}